var express = require('express');
var router = express.Router();
const bcrypt = require('bcryptjs');
const multiparty = require('multiparty');
const fs = require('fs');
const path = require('path');
const { pool } = require('../shamall/db');
const { generateAccessToken, generateRefreshToken } = require('./auth');
const { authenticateToken, getUserData, checkDataOwnership } = require('../middleware/authentk');

// 上传图片接口
router.post('/upload-image', authenticateToken, (req, res) => {
  // 创建 multiparty 实例
  const form = new multiparty.Form({
    uploadDir: 'public/uploads/', // 上传目录
    maxFilesSize: 5 * 1024 * 1024, // 限制5MB
    autoFiles: true, // 自动处理文件
    autoFields: true // 自动处理自动
  });

  form.parse(req, async (err, fields, files) => {
    if (err) {
      return res.status(500).json({
        code: 500,
        message: '上传失败',
        errorr: err.message
      });
    }

    try {
      // 检查是否有文件
      if (!files.image || files.image.length === 0) {
        return res.status(400).json({
          code: 400,
          message: '请选择要上传的图片'
        })
      }

      const file = files.image[0]; // 获取第一个文件

      // 检查文件类型
      const allowedTypes = ['image/jpeg', 'image/png', 'image/git', 'image/webp'];
      if (!allowedTypes.includes(file.headers['content-type'])) {
        // 删除上传的文件
        fs.unlinkSync(file.path);
        return res.status(400).json({
          code: 400,
          message: '只允许上传图片文件(JPG、PNG、GIF、WEBP)'
        });
      }

      // 生成唯一文件名
      const ext = path.extname(file.originalFilename);
      const newFilename = `image-${Date.now()}-${Math.random().toString(36).slice(2, 11)}${ext}`;
      const newPath = path.join('public/uploads/', newFilename);

      // 重命名文件
      fs.renameSync(file.path, newPath);

      // 返回图片URL
      const imageUrl = `http://localhost:4000/uploads/${newFilename}`;

      res.json({
        code: 200,
        message: '上传成功',
        data: {
          url: imageUrl,
          filename: newFilename
        }
      })
    } catch (error) {
      // 如果出错，删除上传的文件
      if (files.image && files.image[0]) {
        fs.unlinkSync(files.image[0].path);
      }

      res.status(500).json({
        code: 500,
        message: '上传失败',
        error: error.message
      })
    }
  })
})

// 注册接口
router.post('/zhuce', async (req, res, next) => {
  try {
    const { phone, password, role } = req.body;
    console.log({ phone, password, role });
    // 1. 查询数据库中是否已存在该手机号
    const checkSql = 'SELECT * FROM app_login WHERE phone = ?';
    const [rows] = await pool.query(checkSql, [phone]); // 执行查询
    if (rows.length > 0) {
      // 2. 如果已存在，返回错误信息
      return res.json({
        code: 409, // 409 表示冲突
        message: '该手机号已注册'
      });
    }


    // 2.对密码进行加密
    const salt = await bcrypt.genSalt(10); //生成盐，10是加强密度
    const hashPassword = await bcrypt.hash(password, salt); //加密密码


    // 3. 如果不存在，插入新用户
    const sql = 'INSERT INTO app_login (phone, password, role) VALUES (?, ?, ?)';
    const [result] = await pool.query(sql, [phone, hashPassword, role]); // 执行插入
    res.json({
      code: 200,
      message: '注册成功',
      insertId: result.insertId
    });
  } catch (err) {
    console.error('数据库错误:', err); // 打印详细错误
    res.json({
      code: 500,
      message: '注册失败'
    });
  }
});

// 登录接口
router.post('/denglu', async (req, res, next) => {
  // 从请求体中获取用户名和密码
  const { username, password } = req.body;
  try {
    // 查询数据库，判断是否有匹配的用户名和密码
    const sql = 'SELECT * FROM app_login WHERE phone = ?';
    // 执行查询，参数用数组传递，防止SQL注入
    const [rows] = await pool.query(sql, [username]);
    if (rows.length > 0) {
      const users = rows[0];


      // 2.用bcryptjs 校验密码
      const isMatch = await bcrypt.compare(password, users.password); // user.password 是加密后的
      if (!isMatch) {
        // 密码不匹配
        return res.json({
          code: 401,
          message: '用户名或密码错误'
        })
      }
      // 1.校验用户名密码
      const user = {
        id: users.id,
        phone: users.phone,
        role: users.role
      }; // 只放必要信息
      // 2.生成 token
      const accessToken = generateAccessToken(user);
      const refreshToken = generateRefreshToken(user);


      // 如果查到数据，说明登录成功
      res.json({
        code: 200,
        message: '登录成功',
        username: users.phone,
        password: users.password,
        role: users.role,
        accessToken,
        refreshToken
      });
      // console.log('accessToken', accessToken);
      // console.log('refreshToken', refreshToken);
    } else {
      // 如果查不到数据，说明用户名或密码错误
      res.json({
        code: 401, // 401表示未授权
        message: '用户名或密码错误'
      });
    }
  } catch (err) {
    // 捕获异常，返回登录失败
    console.error('数据库错误:', err);
    res.json({
      code: 500,
      message: '登录失败'
    });
  }
});

// 获取所有商品（管理员和用户都可以看到）推荐商品所有
router.get('/all-products', async (req, res) => {
  try {
    const sql = 'SELECT * FROM app_list';
    const [rows] = await pool.query(sql);

    // 关键：images 字段转为数组
    const data = rows.map(item => ({
      ...item,
      images: item.images ? JSON.parse(item.images) : []
    }));

    res.json({
      code: 200,
      data
    });
  } catch (err) {
    res.status(500).json({ message: '获取商品失败' });
  }
})

// 获取用户自己的数据列表
router.get('/list', authenticateToken, getUserData, async (req, res) => {
  try {
    const userId = req.userId;
    const sql = 'SELECT * FROM app_list WHERE app_login_id = ?';
    const [rows] = await pool.query(sql, [userId]);
    const data = rows.map(item => ({
      ...item,
      images: item.images ? JSON.parse(item.images) : []
    }));

    res.json({
      code: 200,
      data
    });
  } catch (err) {
    res.status(500).json({ message: '获取数据失败' });
  }
})

// 添加数据 - 自动关联到当前用户
router.post('/add', authenticateToken, getUserData, async (req, res) => {
  try {
    const userId = req.userId;
    const { images, title, context, price } = req.body;
    const imagesStr = JSON.stringify(images);
    // console.log({ images, title, context, price, userId, imagesStr });
    const sql = 'INSERT INTO app_list (images, title, context, price, app_login_id) VALUES (?, ?, ?, ?, ?)';
    const [result] = await pool.query(sql, [imagesStr, title, context, price, userId]);

    res.json({
      code: 200,
      message: '添加成功',
      data: {
        id: result.insertId
      }
    });
  } catch (err) {
    res.status(500).json({ message: '添加失败' });
  }
});

// 更新数据 - 需要验证所有权
router.put('/update/:id', authenticateToken, getUserData, checkDataOwnership, async (req, res) => {
  try {
    const { id } = req.params;
    const { images, title, context, price } = req.body;

    const sql = 'UPDATE app_list SET images = ?, title = ?, context = ?, price = ? WHERE id = ? AND app_login_id = ?';
    const [result] = await pool.query(sql, [images, title, context, price, id, req.userId]);
    // console.log(result);
    res.json({
      code: 200,
      message: '更新成功',
      // affectedRows: result.affectedRows //告诉前端影响了多少行
    });
  } catch (err) {
    res.status(500).json({
      message: '更新失败'
    })
  }
});

// 删除数据 - 需要验证所有权
router.delete('/delete/:id', authenticateToken, getUserData, checkDataOwnership, async (req, res) => {
  try {
    const { id } = req.params;

    const sql = 'DELETE FROM app_list WHERE id = ? AND app_login_id = ?';
    const [result] = await pool.query(sql, [id, req.userId]);
    // console.log(result);
    res.json({
      code: 200,
      message: '删除成功',
      // affectedRows: result,affectedRows //告诉前端影响了多少行
    });
  } catch (err) {
    res.status(500).json({
      message: '删除失败'
    });
  }
});

module.exports = router;